﻿using MicroAmoy.Application.Code;
using MicroAmoy.Application.Entity.CustomerManage;
using MicroAmoy.Application.IService.CustomerManage;
using MicroAmoy.Application.Service.SystemManage;
using MicroAmoy.Data.Repository;
using MicroAmoy.Util;
using MicroAmoy.Util.Extension;
using MicroAmoy.Util.WebControl;
using Senparc.Weixin.MP.AdvancedAPIs;
using Senparc.Weixin.MP.AdvancedAPIs.OAuth;
using System;
using System.Collections.Generic;
using System.Linq;
using MicroAmoy.Util.Log;
using Comm = MicroAmoy.Util.WeChat.Comm;
using System.Data.Common;
using System.Data.SqlClient;
using System.Data;

namespace MicroAmoy.Application.Service.CustomerManage
{
    /// <summary>
    /// 版 本 6.1
    /// Copyright (c) 2013-2016 云云科技工作室
    /// 创 建：超级管理员
    /// 日 期：2017-03-25 22:29
    /// 描 述：会员管理类
    /// </summary>
    public class MACustomerService : RepositoryFactory<MACustomerEntity>, IMACustomerIService
    {
        #region 获取数据
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="queryJson">查询参数</param>
        /// <returns>返回列表</returns>
        public IEnumerable<MACustomerEntity> GetList(string queryJson)
        {
            return this.BaseRepository().IQueryable().ToList();
        }
        public MACustomerEntity FindObject(string strSql)
        {
            return this.BaseRepository().FindList(strSql).FirstOrDefault();
        }
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="pagination">分页</param>
        /// <param name="queryJson">查询参数</param>
        /// <returns>返回分页列表</returns>
        public IEnumerable<MACustomerEntity> GetPageList(Pagination pagination, string queryJson)
        {
            var expression = LinqExtensions.True<MACustomerEntity>();
            var queryParam = queryJson.ToJObject();
            //查询条件
            if (!queryParam["condition"].IsEmpty() && !queryParam["keyword"].IsEmpty())
            {
                string condition = queryParam["condition"].ToString();
                string keyword = queryParam["keyword"].ToString();
                switch (condition)
                {
                    //case "EnCode":              //客户编号
                    //    expression = expression.And(t => t.EnCode.Contains(keyword));
                    //    break;
                    case "Name":            //客户名称
                        expression = expression.And(t => t.Name.Contains(keyword));
                        break;
                    case "Mobile":             //联系人
                        expression = expression.And(t => t.Mobile.Contains(keyword));
                        break;
                    default:
                        break;
                }
            }
            return this.BaseRepository().FindList(expression, pagination);
        }
        /// <summary>
        /// 获取实体
        /// </summary>
        /// <param name="keyValue">主键值</param>
        /// <returns></returns>
        public MACustomerEntity GetEntity(string keyValue)
        {
            return this.BaseRepository().FindEntity(keyValue);
        }
        #endregion

        #region 提交数据
        /// <summary>
        /// 删除数据
        /// </summary>
        /// <param name="keyValue">主键</param>
        public void RemoveForm(string keyValue)
        {
            this.BaseRepository().Delete(keyValue);
        }
        /// <summary>
        /// 保存表单（新增、修改）
        /// </summary>
        /// <param name="keyValue">主键值</param>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public void SaveForm(string keyValue, MACustomerEntity entity)
        {
            if (!string.IsNullOrEmpty(keyValue))
            {
                entity.Modify(keyValue);
                this.BaseRepository().Update(entity);
            }
            else
            {
                entity.Create();
                this.BaseRepository().Insert(entity);
            }
        }
        private Log _logger;
        public Log Logger
        {
            get { return _logger ?? (_logger = LogFactory.GetLogger(this.GetType().ToString())); }
        }
        public void SetTickets(string openid, string name)
        {
            MACustomerEntity model = this.FindObject(string.Format("select * from MA_Customer where OpenId='{0}'", openid));
            if (model == null)
            {
                string sql = @"insert into MA_Customer(Id,Name,OpenId,Number,IsDeleted,CreateDate)
                values(@Id,@Name,@OpenId,@Number,@IsDeleted,@CreateDate)";
                  SqlParameter[] paras = new SqlParameter[6]{
                   new SqlParameter("@Id",Guid.NewGuid().ToString()),
                   new SqlParameter("@Name",name),
                   new SqlParameter("@OpenId",openid),
                   new SqlParameter("@Number",5),
                   new SqlParameter("@IsDeleted",Convert.ToInt32(0)),
                   new SqlParameter("@CreateDate",DateTime.Now)
                };
                int value=this.BaseRepository().ExecuteBySql(sql, paras);
                model = this.FindObject(string.Format("select * from MA_Customer where OpenId='{0}'", openid));
                Logger.Info(openid + "--------" + name + "===" + DateTime.Now);
            }
            WechatOperator operators = new WechatOperator()
            {
                Code = model.EnCode,
                UserId = model.Id,
                UserName = model.Name,
                LogTime = System.DateTime.Now,
                Number=model.Number,
                Token = DESEncrypt.Encrypt(System.Guid.NewGuid().ToString()),
            };
            WechatProvider.Provider.AddCurrent(operators);
        }
        public bool Auth(string code)
        {
            var token = OAuthApi.GetAccessToken(Comm.Config.APPKEY, Comm.Config.APPSECRET, code);
            if (token == null) return false;
            OAuthUserInfo user = OAuthApi.GetUserInfo(token.access_token, token.openid);

            SetTickets(user.openid, user.nickname);
            return true;
        }
        #endregion
    }
}
